package vg.com.search_friend;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vg.com.chatonline.activity.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import ce51.dunghn.imagethread.ExtendedImageDownloader;

import com.dunghn.loadtest.JsonParse;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class SearchFriendsTab1 extends Activity {
	EditText edt;
	Button btn;
	ListView lv;
	ImageLoader imageLoader = ImageLoader.getInstance();
	DisplayImageOptions options;
	String url = "http://deduocyeu.com/json/getUserStatus.php?pagesize=200";
	ArrayList<HashMap<String, String>> contact;
	ArrayList<HashMap<String, String>> contact_sort = new ArrayList<HashMap<String, String>>();
	ContactAdapter adapter;
	String input;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		setContentView(R.layout.ac_serchfriends_tab);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.stub_image)
				.showImageForEmptyUri(R.drawable.image_for_empty_url)
				.cacheInMemory().cacheOnDisc()
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		edt = (EditText) findViewById(R.id.searchfriend_edt);
		btn = (Button) findViewById(R.id.searchfriend_btn);
		lv = (ListView) findViewById(R.id.searchfriend_lv);

		edt.setHint("Nhập tên bạn muốn tìm");

		btn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				input = edt.getText().toString().toLowerCase();
				if (!input.equals("")) {
					new SearchTask().execute();
				}
			}
		});

		// Set su kien khi click len item
		lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(),
						contact_sort.get(arg2).get("use_fullname"),
						Toast.LENGTH_LONG).show();
			}
		});
	}

	// Task tim kiem, chay ngam, tim va tra ve ket qua, hien thi len listview
	class SearchTask extends AsyncTask<Void, Void, Void> {
		ProgressDialog pdRing;

		@Override
		protected void onPreExecute() {
			pdRing = ProgressDialog.show(SearchFriendsTab1.this, null, null);
			pdRing.setContentView(R.layout.custom_dialog_login);
			pdRing.setCancelable(true);
		}

		@Override
		protected Void doInBackground(Void... v) {
			contact = new ArrayList<HashMap<String, String>>();
			contact = loadContactData(url);
			return null;
		}

		@Override
		protected void onPostExecute(Void v) {
			pdRing.dismiss();

			contact_sort.clear();
			for (int i = 0; i < contact.size(); i++) {
				String s = contact.get(i).get("use_fullname").toLowerCase();
				if (s.contains(input)) {
					contact_sort.add(contact.get(i));
				}
			}
			adapter = new ContactAdapter(getApplicationContext(), contact_sort);
			lv.setAdapter(adapter);
			if (contact_sort.isEmpty()) {
				Toast.makeText(getBaseContext(), "Khong tim thay ket qua",
						Toast.LENGTH_LONG).show();
			}
		}
	};

	// load du lieu tu json
	public ArrayList<HashMap<String, String>> loadContactData(String url) {
		ArrayList<HashMap<String, String>> contact_list = new ArrayList<HashMap<String, String>>();
		JSONArray data = new JSONArray();
		JsonParse js = new JsonParse();
		JSONObject jso = new JSONObject();
		jso = js.getJSONFromUrl(url);
		try {
			data = jso.getJSONArray("data");
			for (int i = 0; i < data.length(); i++) {
				JSONObject obj = data.getJSONObject(i);
				String name = obj.getString("use_fullname");
				String image = obj.getString("use_avatar");
				HashMap<String, String> arr = new HashMap<String, String>();
				arr.put("use_fullname", name);
				arr.put("use_avatar", image);

				contact_list.add(arr);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return contact_list;
	}

	// Adapter cho lisview
	public class ContactAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		Context c;
		ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();

		public ContactAdapter(Context context,
				ArrayList<HashMap<String, String>> d) {
			c = context;
			data = d;
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return data.get(position);
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View vi = convertView;
			if (convertView == null) {
				vi = inflater.inflate(R.layout.custom_lv_contact, null);
			}
			TextView txtView = (TextView) vi
					.findViewById(R.id.contact_txt_name);
			ImageView imageView = (ImageView) vi
					.findViewById(R.id.contact_img_avatar);
			DisplayMetrics metrics = getResources().getDisplayMetrics();
			int width = metrics.widthPixels;

			LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
					width / 6, width / 6);
			imageView.setLayoutParams(layout);

			txtView.setText(data.get(position).get("use_fullname"));
			ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
					getApplicationContext())
					.threadPriority(Thread.NORM_PRIORITY - 2)
					.memoryCacheSize(2 * 1024 * 1024)
					.denyCacheImageMultipleSizesInMemory()
					.discCacheFileNameGenerator(new Md5FileNameGenerator())
					.imageDownloader(
							new ExtendedImageDownloader(getApplicationContext()))
					.tasksProcessingOrder(QueueProcessingType.LIFO)
					.enableLogging().build();
			ImageLoader.getInstance().init(config);
			imageLoader.displayImage(data.get(position).get("use_avatar"),
					imageView, options);

			return vi;
		}
	}
}
